package com.demo.springBootDemo07.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.demo.springBootDemo07.entity.Dept;
import com.demo.springBootDemo07.service.DeptService;

@Service
public class DeptServiceImpl implements DeptService {

	@Autowired
	private StringRedisTemplate template;

	// 通过spring-boot-autoconfigure，
	// 已向spring容器自动注册 RedisTemplate<Object,Object>(name="redisTemplate")
	// 和StringRedisTemplate(name="stringRedisTemplate")
	@Resource(name = "stringRedisTemplate") //
	private ValueOperations<String, String> ops;

	private static final String DOMAIN = "DEPT";
	private static final String KEY_PATTERN = "%s:%s"; // key为"表名:PKID"的格式

	@Override
	public List<Dept> findList() {
		List<Dept> list = new ArrayList<>();
		String key = String.format(KEY_PATTERN, DOMAIN, "*");
		Set<String> keys = this.template.keys(key);
		List<String> deptStrList = this.ops.multiGet(keys);
		for (String deptStr : deptStrList) {
			Dept dept = JSON.parseObject(deptStr, Dept.class);
			list.add(dept);
		}
		return list;
	}

	@Override
	public Dept getByPrimaryKey(Integer deptno) {
		Dept dept = null;
		String key = String.format(KEY_PATTERN, DOMAIN, deptno);
		if (this.template.hasKey(key)) {
			String deptStr = this.ops.get(key); // get
			dept = JSON.parseObject(deptStr, Dept.class);
		}
		return dept;
	}

	@Override
	public Dept addDept(final Dept dept) {
		String key = String.format(KEY_PATTERN, DOMAIN, dept.getDeptno());
		this.ops.set(key, JSON.toJSONString(dept)); // add
		return dept;
	}

	@Override
	public Dept updateDept(final Integer deptno, final Dept dept) {
		Dept deptOrg = null;
		String key = String.format(KEY_PATTERN, DOMAIN, deptno);
		if (this.template.hasKey(key)) {
			String deptStr = this.ops.get(key);
			deptOrg = JSON.parseObject(deptStr, Dept.class);

			this.ops.set(key, JSON.toJSONString(dept)); // update
		}
		return deptOrg;
	}

	@Override
	public Dept deleteByPrimaryKey(final Integer deptno) {
		Dept deptOrg = null;
		String key = String.format(KEY_PATTERN, DOMAIN, deptno);
		if (this.template.hasKey(key)) {
			String deptStr = this.ops.get(key);
			deptOrg = JSON.parseObject(deptStr, Dept.class);

			this.template.delete(key); // delete
		}
		return deptOrg;
	}

}
